import { defineStore } from 'pinia'
import { reactive, computed, toRefs } from 'vue'

// 主题类型
export type ThemeType = 'light' | 'dark' | 'blue'

// 主题配置接口
interface ThemeState {
  currentTheme: ThemeType
}

export const useThemeStore = defineStore('theme', () => {
  // 从localStorage获取主题设置，如果没有则使用默认主题
  const savedTheme = localStorage.getItem('theme') as ThemeType | null
  const defaultTheme = 'light' as ThemeType
  
  const state = reactive<ThemeState>({
    currentTheme: savedTheme || defaultTheme
  })
  
  // 获取当前主题
  const getCurrentTheme = computed(() => state.currentTheme)
  
  // 切换主题
  const toggleTheme = (): void => {
    const themes: ThemeType[] = ['light', 'dark', 'blue']
    const currentIndex = themes.indexOf(state.currentTheme)
    const newIndex = (currentIndex + 1) % themes.length
    setTheme(themes[newIndex])
  }
  
  // 设置主题
  const setTheme = (theme: ThemeType): void => {
    state.currentTheme = theme
    localStorage.setItem('theme', theme)
    
    // 更新HTML元素的data-theme属性
    document.documentElement.setAttribute('data-theme', theme)
    
    // 移除所有主题类
    document.documentElement.classList.remove('light', 'dark', 'blue')
    
    // 添加当前主题类
    document.documentElement.classList.add(theme)
  }
  
  // 初始化主题
  const initTheme = (): void => {
    setTheme(state.currentTheme)
  }
  
  return {
    ...toRefs(state),
    getCurrentTheme,
    toggleTheme,
    setTheme,
    initTheme
  }
})